{% extends "layout.html" %}
{% set active_page = "graph_async" %}
{% set help_page = ["https://kizniche.github.io/Mycodo/Data-Viewing/#asynchronous-graphs", _('Asynchronous Graphs')] %}

{% block head %}
  <script type="text/javascript" src="/static/js/user_js/highstock-9.1.2.js"></script>
  <script type="text/javascript" src="/static/js/user_js/highcharts-more-9.1.2.js"></script>
  <script type="text/javascript" src="/static/js/user_js/data-9.1.2.js"></script>
  <script type="text/javascript" src="/static/js/user_js/exporting-9.1.2.js"></script>
  <script type="text/javascript" src="/static/js/user_js/export-data-9.1.2.js"></script>
  <script type="text/javascript" src="/static/js/user_js/offline-exporting-9.1.2.js"></script>

  {% if current_user.theme in dark_themes %}
    <script src="/static/js/dark-unica-custom.js"></script>
  {% endif %}
{% endblock %}

{% block title %} - {{_('Asynchronous Graph')}}{% endblock %}

{% block body %}
  <!-- Route: /graph-async -->

  <div class="container">
  {% include 'flash_messages.html' %}

    <h4>{{_('Asynchronous Graphs')}} <a href="{{help_page[0]}}" target="_blank"><span style="font-size: 16px" class="fas fa-question-circle"></span></a></h4>

    <p>A graphical data display that is useful for viewing data sets spanning relatively long periods of time (weeks/months/years), which could be very data- and processor-intensive to view as a Synchronous Graph.</p>

  {% if selected_ids_measures %}
  </div>

  <div id="container" style="height: {{async_height}}px; min-width: 300px"></div>

  <div class="container">
  {% endif %}

    <form method="post" action="/graph-async">
    <div class="form-row" style="padding: 1em 0">
      <div class="col-auto">
        Height:
      </div>
      <div class="col-auto">
        <input class="form-control" id="async_height" name="async_height" type="number" value="{{async_height}}">
      </div>
      <div class="col-auto">
        <input class="btn btn-primary" type="submit" name="submit" value="All Data">
      </div>
      <div class="col-auto">
        Past:
      </div>
      <div class="col-auto">
        <input class="btn btn-primary" type="submit" name="submit" value="Year">
      </div>
      <div class="col-auto">
        <input class="btn btn-primary" type="submit" name="submit" value="Month">
      </div>
      <div class="col-auto">
        <input class="btn btn-primary" type="submit" name="submit" value="Week">
      </div>
      <div class="col-auto">
        <input class="btn btn-primary" type="submit" name="submit" value="Day">
      </div>
    </div>
    <div class="row">
      <div class="col-auto">
        <select class="form-control" id="selected_measure" name="selected_measure" size="{{choices_input|length + choices_function|length + choices_output|length + choices_pid|length + choices_tag|length}}" multiple>
        {% for each_input_form in choices_input -%}
          <option value="{{each_input_form['value']}},input"{% if each_input_form['value'] + ',input' in selected_ids_measures %} selected{% endif %}>{{each_input_form['item']}}</option>
        {% endfor -%}
        {% for each_function_form in choices_function -%}
          <option value="{{each_function_form['value']}},function"{% if each_function_form['value'] + ',function' in selected_ids_measures %} selected{% endif %}>{{each_function_form['item']}}</option>
        {% endfor -%}
        {% for each_output_form in choices_output -%}
          <option value="{{each_output_form['value']}},output"{% if each_output_form['value'] + ',output' in selected_ids_measures %} selected{% endif %}>{{each_output_form['item']}}</option>
        {% endfor -%}
        {% for each_pid_form in choices_pid -%}
          <option value="{{each_pid_form['value']}},pid"{% if each_pid_form['value'] + ',pid' in selected_ids_measures %} selected{% endif %}>{{each_pid_form['item']}}</option>
        {% endfor -%}
        {% for each_tag_form in choices_tag -%}
          <option value="{{each_tag_form['value']}},tag"{% if each_tag_form['value'] + ',tag' in selected_ids_measures %} selected{% endif %}>{{each_tag_form['item']}}</option>
        {% endfor -%}
        </select>
      </div>
    </div>
    </form>

  <div style="padding-bottom: 1em">
    {{_('Hold down the <kbd>Ctrl</kbd> or <kbd>&#8984;</kbd> key to select more than one')}}
  </div>

  </div>

  {% if selected_ids_measures %}
  <script>
Highcharts.setOptions({
  global: {
    useUTC: false
  },
  lang: {
    thousandsSep: ','
  }
});

$(document).ready(function() {
    const id_measure = [
    {% for each_id_meas in selected_ids_measures %}
    {
      device_id: '{{each_id_meas.split(',')[0]}}',
      measurement_id: '{{each_id_meas.split(',')[1]}}',
      device_type: '{{each_id_meas.split(',')[2]}}'
    },
    {% endfor %}
    ];
    let chart = [];

    function getPastData(chart_number, series, device_id, device_type, measurement_id, start_time) {
      const url = '/async/' + device_id + '/' + device_type + '/' + measurement_id + '/' + start_time + '/0';
      $.getJSON(url,
        function(data, responseText, jqXHR) {
          if (jqXHR.status !== 204) {

            let new_data = [];
            for (let i = 0; i < data.length; i++) {
              let new_date = new Date(data[i][0] * 1000);
              let new_time = new_date.getTime();

              if (device_type === 'tag') {
                chart[chart_number].series[series].addPoint({
                  x: new_time,
                  title: data[i][1],
                  text: data[i][2].replace(/(?:\r\n|\r|\n)/g, "<br/>").replace(/  /g, '\u2591\u2591')
                }, false, false);
              }
              else {
                new_data.push([new_time, data[i][1]]);
              }
            }

            if (device_type !== 'tag') {
              new_data.push([new Date().getTime(), null]);
              chart[chart_number].series[series].setData(new_data, false, false);
              let nav = chart[chart_number].get('navigator');
              nav.setData(new_data, false, false);
            }

          }
          if (device_type !== 'tag') {
            chart[chart_number].redraw();
          }
        }
      );
    }

    function set_data_from_url(url, series, device_type) {
      $.getJSON(url,
        function (data, responseText, jqXHR) {
          let new_data = [];
          if (jqXHR.status !== 204) {
            for (let i = 0; i < data.length; i++) {
              const new_date = new Date(data[i][0] * 1000);
              const new_time = new_date.getTime();
              if (device_type === 'tag') {
                chart[0].series[series].addPoint({
                  x: new_time,
                  title: data[i][1],
                  text: data[i][2].replace(/(?:\r\n|\r|\n)/g, "<br/>").replace(/  /g, '\u2591\u2591')
                }, false, false);
              }
              else {
                new_data.push([new_time, data[i][1]]);
              }
            }
          }
          if (device_type !== 'tag') chart[0].series[series].setData(new_data);
          chart[0].hideLoading();
        }
      );
    }

    function updateAllSeries(e) {
      let min = null;
      let max = null;
      if (e.xAxis == null) {
        min = e.min;
        max = e.max;
      } else {
        min = e.xAxis[0].min;
        max = e.xAxis[0].max;
      }
      for (let each_series in id_measure) {
        if (id_measure[each_series]['device_type'] !== 'tag') {
          const url = '/async/' + id_measure[each_series]['device_id'] + '/' + id_measure[each_series]['device_type'] + '/' + id_measure[each_series]['measurement_id'] + '/' + Math.round(min) / 1000 + '/' + Math.round(max) / 1000;
          set_data_from_url(url, each_series, id_measure[each_series]['device_type'])
        }
      }
    }

    // create the chart
    chart[0] = new Highcharts.StockChart({
        chart: {
          renderTo: 'container',
          zoomType: 'x',
          events: {
            load: function () {
              {% set count_series = [] -%}
              {% for each_id_meas in selected_ids_measures %}
                {%- set device_id = each_id_meas.split(',')[0] -%}
                {%- set measurement_id = each_id_meas.split(',')[1] -%}
                {%- set device_type = each_id_meas.split(',')[2] -%}
              getPastData(0, {{count_series|count}}, '{{device_id}}', '{{device_type}}', '{{measurement_id}}', '{{start_time_epoch}}');
                {%- do count_series.append(1) %}
              {% endfor %}
            },
            selection: updateAllSeries
          }
        },

        tooltip: {
          shared: true,
          formatter: function(){
            const d = new Date(this.x);
            if (this.point) {
              return '<b>'+ Highcharts.dateFormat('%B %e, %Y %H:%M:%S.', this.x) + d.getMilliseconds()
                   + '</b><br/>' + this.series.name
                   + '<br/>' + this.point.title
                   + '<br/>' + this.point.text;
            }
            else {
              let s = '<b>'+ Highcharts.dateFormat('%B %e, %Y %H:%M:%S.', this.x) + d.getMilliseconds() + '</b>';
              $.each(this.points, function(i, point) {
                  s += '<br/><span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': ' + Highcharts.numberFormat(point.y, this.series.tooltipOptions.valueDecimals) + ' ' + this.series.tooltipOptions.valueSuffix;
              });
              return s;
            }
          }
        },

        navigator: {
            adaptToUpdatedData: false,
            series: {
                id: 'navigator'
            }
        },

        scrollbar: {
          liveRedraw: false
        },

        legend: {
          enabled: true
        },

        // subtitle: {
        //     text: 'Display many data points'
        // },

        rangeSelector: {
            buttons: [{
                type: 'hour',
                count: 1,
                text: '1h'
            }, {
                type: 'day',
                count: 1,
                text: '1d'
            }, {
                type: 'week',
                count: 1,
                text: '1w'
            }, {
                type: 'month',
                count: 1,
                text: '1m'
            }, {
                type: 'year',
                count: 1,
                text: '1y'
            }, {
                type: 'all',
                text: 'All'
            }],
            inputEnabled: false, // it supports only days
            selected: 4 // all
        },

        xAxis: {
          events: {
            setExtremes: function(e) {
              if (typeof(e.rangeSelectorButton) !== 'undefined' || e.trigger === 'navigator') updateAllSeries(e);
            }
          },
          minRange: 1800 * 1000 // 30 minutes
        },

        yAxis: [
        {% for each_axis in y_axes if dict_units and each_axis in dict_units %}
          {
            title: {
              text: '{{dict_units[each_axis]['name']}}{% if dict_units[each_axis]['unit'] != '' %} ({{dict_units[each_axis]['unit']}}){% endif %}'
            },
            labels: {
              format: '{value}'
            },
            opposite: false,
            id: '{{each_axis}}'
          },
        {% endfor %}
        ],

        credits: {
          enabled: false,
          href: "https://github.com/kizniche/Mycodo",
          text: "Mycodo"
        },

        series: [

        {% for each_id_meas in selected_ids_measures -%}
          {%- set device_id = each_id_meas.split(',')[0] -%}
          {%- set measurement_id = each_id_meas.split(',')[1] -%}

          {% for each_input in input if each_input.unique_id == device_id -%}
            {%- if measurement_id in device_measurements_dict -%}

            {
              name: '{{each_input.name}}

                {%- if device_measurements_dict[measurement_id].name -%}
                  {{' (' + device_measurements_dict[measurement_id].name}})
                {%- endif -%}

                {{' (CH' + (device_measurements_dict[measurement_id].channel)|string}}

                {%- if dict_measure_measurements[measurement_id] in dict_measurements and
                 dict_measurements[dict_measure_measurements[measurement_id]]['name'] -%}
                  {{', ' + dict_measurements[dict_measure_measurements[measurement_id]]['name']}}
                {%- endif -%}

                {%- if dict_measure_units[measurement_id] in dict_units and
                       dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                  {{', ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}

                )',

              {% if dict_measure_measurements[measurement_id] in dict_measurements and
                    dict_measurements[dict_measure_measurements[measurement_id]]['meas'] == 'edge' %}
              type: 'column',
              {% else %}
              type: 'line',
              {% endif %}
              tooltip: {
                valueSuffix: '
                {%- if dict_measure_units[measurement_id] in dict_units and
                     dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                {{' ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}
                ',
                valueDecimals: 3
              },
              yAxis: '
                {%- if measurement_id in dict_measure_units -%}
                  {{dict_measure_units[measurement_id]}}
                {%- endif -%}
                  ',
              data: []
            },

            {%- endif -%}
          {% endfor %}

          {% for each_function in function if each_function.unique_id == each_id_meas.split(',')[0] -%}
            {%- set measurement_id = each_id_meas.split(',')[1] -%}
            {%- if measurement_id in device_measurements_dict -%}

            {
            name: '{{each_function.name}}

              {%- if device_measurements_dict[measurement_id].name -%}
                {{' (' + device_measurements_dict[measurement_id].name}})
              {%- endif -%}

                {{' (CH' + (device_measurements_dict[measurement_id].channel)|string}}

              {%- if dict_measure_measurements[measurement_id] in dict_measurements and
               dict_measurements[dict_measure_measurements[measurement_id]]['name'] -%}
                {{', ' + dict_measurements[dict_measure_measurements[measurement_id]]['name']}}
              {%- endif -%}

              {%- if dict_measure_units[measurement_id] in dict_units and
                     dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                {{', ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
              {%- endif -%}

              )',

            {% if dict_measure_measurements[measurement_id] in dict_measurements and
                  dict_measurements[dict_measure_measurements[measurement_id]]['meas'] == 'edge' %}
            type: 'column',
            {% else %}
            type: 'line',
            {% endif %}
            tooltip: {
              valueSuffix: '
              {%- if dict_measure_units[measurement_id] in dict_units and
                     dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                {{' ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
              {%- endif -%}
              ',
              valueDecimals: 3
            },
            yAxis: '
              {%- if measurement_id in dict_measure_units -%}
                {{dict_measure_units[measurement_id]}}
              {%- endif -%}
                ',
            data: []
          },
            {%- endif -%}
          {% endfor %}

          {%- for each_pid in pid if each_pid.unique_id == device_id -%}
            {%- if measurement_id in device_measurements_dict -%}

            {
              name: '{{each_pid.name}}

                {%- if device_measurements_dict[measurement_id].name -%}
                  {{' (' + device_measurements_dict[measurement_id].name}})
                {%- endif -%}

                  {{' (CH' + (device_measurements_dict[measurement_id].channel)|string}}

                {%- if dict_measure_measurements[measurement_id] in dict_measurements and
                 dict_measurements[dict_measure_measurements[measurement_id]]['name'] -%}
                  {{', ' + dict_measurements[dict_measure_measurements[measurement_id]]['name']}}
                {%- endif -%}

                {%- if dict_measure_units[measurement_id] in dict_units and
                       dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                  {{', ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}

                )',

              {% if dict_measure_measurements[measurement_id] in dict_measurements and
                    dict_measurements[dict_measure_measurements[measurement_id]]['meas'] == 'edge' %}
              type: 'column',
              {% else %}
              type: 'line',
              {% endif %}
              tooltip: {
                valueSuffix: '
                {%- if dict_measure_units[measurement_id] in dict_units and
                       dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                  {{' ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}
                ',
                valueDecimals: 3
              },
              yAxis: '
                {%- if measurement_id in dict_measure_units -%}
                  {{dict_measure_units[measurement_id]}}
                {%- endif -%}
                  ',
              data: []
            },

            {%- endif -%}
          {% endfor %}

          {%- for each_output in output if each_output.unique_id == device_id -%}
            {%- if measurement_id in device_measurements_dict -%}

            {
              name: '{{each_output.name}}

                {%- if device_measurements_dict[measurement_id].name -%}
                  {{' (' + device_measurements_dict[measurement_id].name}})
                {%- endif -%}

                  {{' (CH' + (device_measurements_dict[measurement_id].channel)|string}}

                {%- if dict_measure_measurements[measurement_id] in dict_measurements and
                 dict_measurements[dict_measure_measurements[measurement_id]]['name'] -%}
                  {{', ' + dict_measurements[dict_measure_measurements[measurement_id]]['name']}}
                {%- endif -%}

                {%- if dict_measure_units[measurement_id] in dict_units and
                       dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                  {{', ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}

                )',

              type: 'column',
              tooltip: {
                valueSuffix: '
                {%- if dict_measure_units[measurement_id] in dict_units and
                       dict_units[dict_measure_units[measurement_id]]['unit'] -%}
                  {{' ' + dict_units[dict_measure_units[measurement_id]]['unit']}}
                {%- endif -%}
                ',
                valueDecimals: 3
              },
              dataGrouping: {
                enabled: false,
                groupPixelWidth: 2
              },
              yAxis: '
                {%- if measurement_id in dict_measure_units -%}
                  {{dict_measure_units[measurement_id]}}
                {%- endif -%}
                  ',
              data: []
            },

            {%- endif -%}
          {% endfor %}

          {% for each_tag in tag if each_tag.unique_id == device_id %}
            {
              name: 'Note Tag: {{each_tag.name}}',
              type: 'flags',
              data: [],
              shape: 'squarepin'
            },
          {% endfor %}

        {% endfor %}  {# End main for #}

        ]
    });
});
</script>
{% endif %}

{% endblock %}
